package cn.edu.nju.software.android.adapter;

import java.util.ArrayList;

import cn.edu.nju.software.android.activity.CommentActivity;
import cn.edu.nju.software.android.activity.DetailedUserActivity;
import cn.edu.nju.software.android.activity.MainActivity;
import cn.edu.nju.software.android.activity.PictureActivity;
import cn.edu.nju.software.android.activity.R;
import cn.edu.nju.software.android.activity.RetweetActivity;
import cn.edu.nju.software.android.model.Comment;
import cn.edu.nju.software.android.model.Status;
import cn.edu.nju.software.android.model.User;
import cn.edu.nju.software.android.util.AsyncImageLoader;
import cn.edu.nju.software.android.util.DateHelper;
import cn.edu.nju.software.android.util.ImageUtil;
import me.maxwin.view.IListviewCallback;
import cn.edu.nju.software.android.activity.DetailedWeiboActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class CommentListViewAdapter extends ArrayAdapter<Comment> {
	private Status status;
	private Context context;
	private ArrayList<Comment> comments = new ArrayList<Comment>();
	private int pageNum = 1;
	private int nowCount = 0;

	private Handler failureHandler = new Handler(){
		public void handleMessage(Message msg) {
			Toast.makeText(context, "WIFI没有打开", Toast.LENGTH_SHORT).show();
		}
	};
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			notifyDataSetChanged(); // 发送消息通知ListView更新
			nowCount += msg.what;
			((DetailedWeiboActivity) context).onComplete();
			if (nowCount >= status.getCommentsCount()) {
				((IListviewCallback) context).disableLoadFunction();
			} else {
				((IListviewCallback) context).enableLoadFunction();
			}
		}
	};

	public CommentListViewAdapter(Status status, Context context) {
		super(context, R.layout.layout_weibo);
		this.context = context;
		this.status = status;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (position == 0) {
			ImageView userImageView = null;
			Button userTextView = null;
			TextView textView = null;
			ImageView subImageView = null;
			TextView dateTextView = null;
			TextView locationTextView = null;
			TextView sourceTextView = null;
			Button commentButton = null;
			Button retweetButton = null;

			Button originalUserNameButton = null;
			TextView retweetedTextView = null;
			if (status.getRetweetStatus() == null) {
				convertView = inflater.inflate(
						R.layout.layout_weibo_detail_original, parent, false);
				userImageView = (ImageView) convertView
						.findViewById(R.id.detail_head_original);
				userTextView = (Button) convertView
						.findViewById(R.id.detail_name_original);
				textView = (TextView) convertView
						.findViewById(R.id.detail_content_original);
				subImageView = (ImageView) convertView
						.findViewById(R.id.detail_picture_original);
				dateTextView = (TextView) convertView
						.findViewById(R.id.detail_time_original);
				locationTextView = (TextView) convertView
						.findViewById(R.id.detail_location_original);
				sourceTextView = (TextView)convertView.findViewById(R.id.detail_source_original);
				commentButton = (Button) convertView
						.findViewById(R.id.detail_comment_original);
				retweetButton = (Button) convertView
						.findViewById(R.id.detail_retweet_original);

				setListViewListener(convertView, false);
			} else {
				convertView = inflater.inflate(
						R.layout.layout_weibo_detail_retweeted, parent, false);
				userImageView = (ImageView) convertView
						.findViewById(R.id.detail_head_retweeted);
				userTextView = (Button) convertView
						.findViewById(R.id.detail_name_retweeted);
				textView = (TextView) convertView
						.findViewById(R.id.detail_link_retweeted);
				originalUserNameButton = (Button) convertView
						.findViewById(R.id.detail_originalName_retweeted);
				retweetedTextView = (TextView) convertView
						.findViewById(R.id.detail_content_retweeted);
				subImageView = (ImageView) convertView
						.findViewById(R.id.detail_picture_retweeted);
				dateTextView = (TextView) convertView
						.findViewById(R.id.detail_time_retweeted);
				locationTextView = (TextView) convertView
						.findViewById(R.id.detail_location_retweeted);
				sourceTextView = (TextView)convertView.findViewById(R.id.detail_source_retweeted);
				commentButton = (Button) convertView
						.findViewById(R.id.detail_comment_retweeted);
				retweetButton = (Button) convertView
						.findViewById(R.id.detail_retweet_retweeted);

				setListViewListener(convertView, true);
			}
			AsyncImageLoader userImageAsyLoader = new AsyncImageLoader();
			AsyncImageLoader subImageAsyLoader = new AsyncImageLoader();

			Drawable userCachedImage = userImageAsyLoader.loadDrawable(context,failureHandler,
					status.getUser().getProfileImageUrl(), userImageView,
					new AsyncImageLoader.ImageCallback() {
				@Override
				public void imageLoaded(Drawable imageDrawable,
						ImageView imageView, String imageUrl) {
					if(imageDrawable != null)
						imageView.setImageDrawable(ImageUtil.resizeProfilePic(imageDrawable));
				}
			},100, 100);
			if (userCachedImage == null) {
				userImageView.setImageResource(R.drawable.user);
			} else {
				userImageView.setImageDrawable(ImageUtil.resizeProfilePic(userCachedImage));
			}
			if (status.getRetweetStatus() != null) {
				User u = status.getRetweetStatus().getUser();
				if(u != null)
					originalUserNameButton.setText(u.getName());
				else
					originalUserNameButton.setText("");
				if (status.getRetweetStatus().getBmiddle_pic() != null) {
					Drawable subCachedImage = subImageAsyLoader.loadDrawable(
							context,failureHandler,
							status.getRetweetStatus().getBmiddle_pic(),
							subImageView, new AsyncImageLoader.ImageCallback() {
								@Override
								public void imageLoaded(Drawable imageDrawable,
										ImageView imageView, String imageUrl) {
									imageView.setImageDrawable(ImageUtil
											.resizeStatusPic(imageDrawable));
								}

							},1, 500);
					if (subCachedImage == null) {
						subImageView.setImageResource(R.drawable.loading);
					} else {
						subImageView.setImageDrawable(ImageUtil
								.resizeStatusPic(subCachedImage));
					}
				}else{
					LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.parent_layout);
					int index = layout.indexOfChild(subImageView);
					layout.removeViewAt(index);
				}
				retweetedTextView.setText(status.getRetweetStatus().getText());
				if(status.getGeo() != null){
					locationTextView.setText("维度:"+status.getGeo().getLatitude() + ",经度:" + status.getGeo().getLongtitude());
				}else{
					LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.parent_layout);
					int index = layout.indexOfChild(locationTextView);
					layout.removeViewAt(index);
				}
			}else{
				if (status.getBmiddle_pic() != null) {
					Drawable subCachedImage = subImageAsyLoader.loadDrawable(
							context, failureHandler, status.getBmiddle_pic(), subImageView,
							new AsyncImageLoader.ImageCallback() {
								@Override
								public void imageLoaded(Drawable imageDrawable,
										ImageView imageView, String imageUrl) {

									imageView.setImageDrawable(ImageUtil
											.resizeStatusPic(imageDrawable));
								}

							},1, 500);
					if (subCachedImage == null) {
						subImageView.setImageResource(R.drawable.loading);
					} else {
						subImageView.setImageDrawable(ImageUtil
								.resizeStatusPic((subCachedImage)));
					}
				}else{
					LinearLayout layout = (LinearLayout) convertView;
					int index = layout.indexOfChild(subImageView);
					layout.removeViewAt(index);
				}
				if(status.getGeo() != null){
					locationTextView.setText("维度:"+status.getGeo().getLatitude() + ",经度:" + status.getGeo().getLongtitude());
				}else{
					LinearLayout layout = (LinearLayout) convertView;
					int index = layout.indexOfChild(locationTextView);
					layout.removeViewAt(index);
				}
			}
			userTextView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, DetailedUserActivity.class);
					intent.putExtra("user", status.getUser());
					intent.putExtra("parent", MainActivity.class);
					context.startActivity(intent);
				}
			});
			sourceTextView.setText("来自"+status.getSource());
			dateTextView.setText(DateHelper.getDateStr(status.getCreatedAt()));
			textView.setText(status.getText());
			userTextView.setText(status.getUser().getName());
			commentButton.setText("评论(" + status.getCommentsCount() + ")");
			retweetButton.setText("转发(" + status.getRepostsCount() + ")");
		} else {
			convertView = inflater.inflate(R.layout.listview_comment, parent,
					false);
			ImageView userImage = (ImageView) convertView
					.findViewById(R.id.comment_head);
			TextView userNameText = (TextView) convertView
					.findViewById(R.id.comment_name);
			TextView text = (TextView) convertView
					.findViewById(R.id.comment_Text);
			TextView dateText = (TextView) convertView
					.findViewById(R.id.comment_Date);

			AsyncImageLoader userImageAsyLoader = new AsyncImageLoader();

			Comment c = comments.get(position - 1);

			Drawable userCachedImage = userImageAsyLoader.loadDrawable(context,failureHandler,
					c.getUser().getProfileImageUrl(), userImage,
					new AsyncImageLoader.ImageCallback() {
				public void imageLoaded(Drawable imageDrawable,
						ImageView imageView, String imageUrl) {
					if(imageDrawable != null)
						imageView.setImageDrawable(ImageUtil.resizeProfilePic(imageDrawable));
				}
			},100, 100);
			if (userCachedImage == null) {
				userImage.setImageResource(R.drawable.user);
			} else {
				userImage.setImageDrawable(ImageUtil.resizeProfilePic(userCachedImage));
			}

			userNameText.setText(c.getUser().getName());
			text.setText(c.getText());
			dateText.setText(DateHelper.getDateStr(c.getCreatedAt()));
		}
		return convertView;
	}

	@Override
	public int getCount() {
		return comments.size() + 1;
	}

	@Override
	public Comment getItem(int position) {
		// TODO Auto-generated method stub
		return comments.get(position);
	}

	public void getNewestComments() {
		Comment.downloadMoreComments(status.getId(), pageNum++, comments,
				handler);
	}

	private void setListViewListener(View view, final boolean isRetweet) {
		Button name = null;
		if (isRetweet) {
			name = (Button) view.findViewById(R.id.detail_name_retweeted);
		} else {
			name = (Button) view.findViewById(R.id.detail_name_original);
		}
		name.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					((Button) v).setTextColor(context.getResources().getColor(R.color.gray));
				} else {
					((Button) v).setTextColor(context.getResources().getColor(R.color.black));
				}
				return false;
			}
		});

		ImageButton picture = null;
		if (isRetweet) {
			picture = (ImageButton) view.findViewById(R.id.detail_picture_retweeted);
		} else {
			picture = (ImageButton) view.findViewById(R.id.detail_picture_original);
		}
		if (picture != null) {
			picture.setOnTouchListener(new OnTouchListener(){     
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						Intent intent = new Intent(context, PictureActivity.class);
						if(!isRetweet)
							intent.putExtra("picture", status.getOriginal_pic());
						else{
							intent.putExtra("picture", status.getRetweetStatus().getOriginal_pic());
						}
						context.startActivity(intent);
					}
					return false;
				}
			});
		}

		Button comment = null;
		if (isRetweet) {
			comment = (Button) view.findViewById(R.id.detail_comment_retweeted);
		} else {
			comment = (Button) view.findViewById(R.id.detail_comment_original);
		}
		comment.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					((Button) v).setTextColor(context.getResources().getColor(R.color.white));
				} else {
					((Button) v).setTextColor(context.getResources().getColor(R.color.black));
					Intent intent = new Intent(context, CommentActivity.class);
					intent.putExtra("isReply", false);
					intent.putExtra("status_id", status.getId());
					context.startActivity(intent);
				}
				return false;
			}
		});

		Button retweet = null;
		if (isRetweet) {
			retweet = (Button) view.findViewById(R.id.detail_retweet_retweeted);
		} else {
			retweet = (Button) view.findViewById(R.id.detail_retweet_original);
		}
		retweet.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					((Button) v).setTextColor(context.getResources().getColor(R.color.white));
				} else {
					((Button) v).setTextColor(context.getResources().getColor(R.color.black));
					Intent intent = new Intent(context, RetweetActivity.class);
					intent.putExtra("status_id", status.getId());
					context.startActivity(intent);
				}
				return false;
			}
		});

	}


}
